package sk.tuke.constraintbuilder.editor;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.PlatformUI;

import sk.tuke.constraintbuilder.handler.CallEditor;
import sk.tuke.constraintbuilder.handler.ListRefresh;
import sk.tuke.constraintbuilder.model.Constraint;
import sk.tuke.constraintbuilder.model.Model;
import sk.tuke.constraintbuilder.model.Ruleset;
import sk.tuke.constraintbuilder.utils.MyUtils;
import sk.tuke.constraintbuilder.views.RulesetEditorView;

public class RulesetEditorController{
	
	private Ruleset ruleset;
	private RulesetEditorView view;
	private RulesetEditor editor;

	public RulesetEditorController(RulesetEditor editor) {
		this.editor = editor;
		EditorInput editorInput = editor.getEditorInput();
		this.ruleset = (Ruleset) editorInput.getInputElement();
	}
	
	public void setView(RulesetEditorView view){
		this.view = view;
		view.showRuleset(ruleset);
	}
	
	public boolean saveRuleset(String name, String description){
		if(name==null || name.equals("")){
			MessageDialog.openError(PlatformUI.getWorkbench().getModalDialogShellProvider().getShell(), "Save Error", "Ruleset name cannot be empty!");
			return false;
		}
		ruleset.setName(name);
		if(description!=null)ruleset.setDescription(description);
		Model.getModel().addRuleset(ruleset);
		Model.getModel().save(ruleset);
		MyUtils.executeCommand(ListRefresh.COMMAND, editor.getSite());
		editor.getParent().refresh(new EditorInput(ruleset));
		return true;
		
	}
	
	public void callConstraintEditor(String constraintId){
		MyUtils.executeParametrizedCommand(CallEditor.COMMAND, CallEditor.PARAMETER, constraintId, editor.getSite());
	}

	public void addConstraintToRuleset(int id) {
		ruleset.addConstraint(Model.getModel().getConstraintById(id));
	}

	public void removeConstraintFromRuleset(Constraint constraint) {
		ruleset.removeConstraint(constraint);
	}
	
	public Ruleset getRuleset(){
		return ruleset;
	}
}
